<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import httpInstance from "@/utils/http.js";
import {imageRecognitionAPI} from '@/apis/AI'
import type { UploadProps, UploadUserFile } from 'element-plus'


const fileList = ref<UploadUserFile[]>([])

const goodsClass=defineModel("input")
const loading=defineModel("loading")

const getGoodsClass=async (imgUrl)=>{
  await imageRecognitionAPI(imgUrl).then((res)=>{
    goodsClass.value=res.choices[0].message.content.length>10?'没有这种商品':res.choices[0].message.content
  })
  loading.value=false
  console.log(goodsClass.value)
}

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const option={
  headers: {
    'Content-Type': 'multipart/form-data',
  }
}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
      `The limit is 3, you selected ${files.length} files this time, add up to ${
          files.length + uploadFiles.length
      } totally`
  )
}

const handleSuccess=(response: any, uploadFile: UploadFile, uploadFiles: UploadFiles):void =>{
  //console.log(response.data.data)
}

const handleError=(response: any, uploadFile: UploadFile, uploadFiles: UploadFiles):void=>{
  loading.value=false
  if(response.status==413){
    ElMessage({
      type:'error',
      message:'图片太大！'
    })
  }
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
      `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
      () => true,
      () => false
  )
}

const uploadImage=async (options)=>{
  const formData = new FormData()
  formData.append('file',options.file)
  loading.value=true
  const response = await httpInstance({
    method: 'post',
    url: `/goods/identify`,
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    }
  })
  fileList.value=[]
  console.log('imgUrl',response.data)
  getGoodsClass(response.data)

}

</script>
<template>
  <el-upload
      v-model:file-list="fileList"
      :headers="option"
      class="upload-demo"
      :http-request="uploadImage"
      :show-file-list="false"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-remove="beforeRemove"
      :limit="1"
      :on-exceed="handleExceed"
  >
    <el-icon size="20" class="camera" ><Camera /></el-icon>
  </el-upload>

</template>
<style scoped>

</style>